import React, { useState, useEffect } from 'react';
import styles from './index.module.scss';

/**
 * 视频占位符组件 - 优化背景图加载性能
 */
const VideoPlaceholder = ({ firstFrameUrl, historyId, visibleVideos }) => {
  const [isImageLoaded, setIsImageLoaded] = useState(false);
  const [shouldLoadImage, setShouldLoadImage] = useState(false);

  // 使用Intersection Observer实现图片懒加载
  useEffect(() => {
    const observer = new IntersectionObserver(
      entries => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            setShouldLoadImage(true);
            observer.disconnect(); // 加载后断开观察
          }
        });
      },
      {
        rootMargin: '200px 0px', // 提前200px开始加载
        threshold: 0.1,
      }
    );

    const placeholderElement = document.querySelector(`[data-placeholder-id="${historyId}"]`);
    if (placeholderElement) {
      observer.observe(placeholderElement);
    }

    return () => observer.disconnect();
  }, [historyId]);

  // 图片加载完成处理
  const handleImageLoad = () => {
    setIsImageLoaded(true);
  };

  // 图片加载失败处理
  const handleImageError = () => {
    console.warn(`背景图加载失败: ${firstFrameUrl}`);
  };

  return (
    <div className={styles.videoPlaceholder} data-placeholder-id={historyId}>
      {/* 条件渲染背景图 */}
      {shouldLoadImage && firstFrameUrl && (
        <img
          src={firstFrameUrl}
          alt="视频封面"
          onLoad={handleImageLoad}
          onError={handleImageError}
          style={{ display: 'none' }} // 隐藏但加载图片
        />
      )}

      {/* 背景样式 */}
      <div
        className={styles.placeholderBackground}
        style={{
          backgroundImage: shouldLoadImage && isImageLoaded ? `url(${firstFrameUrl})` : 'none',
          backgroundColor: !isImageLoaded ? '#f5f5f5' : 'transparent',
        }}>
        <div className={styles.placeholderContent}>
          {!isImageLoaded ? '加载中...' : '点击加载视频'}
        </div>
      </div>
    </div>
  );
};

export default VideoPlaceholder;
